var siphash = require("siphash")
const assert = require('assert')
const l = console.log
let vector = [0,0,0,0]




function test(){
	// 单参数测试
	let rid = '13o93906E89G01'
	let expect = 'accbc5e06028b208'
	let hashval = sipHash64(rid)
	assert.equal(hashval,expect,'单参数测试失败')
	
	// 二参数测试
	rid = ['13o93906E89G01','13o93906E89G02']
	expect = 'c602a54a7d2e3326'
	hashval = sipHash64(...rid)
	assert.equal(hashval,expect,'二参数测试失败')
	
	// 三参数测试
	rid = ['13o93906E89G01','13o93906E89G02','13o93914E89G05']
	expect = 'ce7b2214a04af75b'
	hashval = sipHash64(...rid)
	assert.equal(hashval,expect,'三参数测试失败')
	
	l('测试成功')
}
test()




// 主函数，功能同clickhouse
function sipHash64(){
	let params = Array.from(arguments)
	if(params.length < 1) return ''
	if(params.length == 1) return hash(params[0])
	
	let hashs = hash(...arguments)
	while(hashs.length > 1){
		hashs[0] = hash(combine(hashs[0],hashs[1]))
		hashs.splice(1,1)
	}
	return hashs[0]
}


// 把16进制字符串格式化成8位buf（大于8位者不剪切）    输入 'abc'   输出 <buffer 0a bc 00 00 00 00 00 00>
function hexStrToBuf(str,size=8,reverse=true){	
	let hexArr = []
	if(str.length%2 == 1) str = '0' + str
	str = str.padEnd(2*size,0)
	for (var i = 0; i < str.length; i++) {
		if(i != 0 && i%2 == 1) hexArr.push(eval('0x'+str[i-1]+str[i])) 
	}
	reverse && (hexArr = hexArr.reverse())
	return Buffer.from(hexArr)
}

// 把十六进制字符串存入内存并合并内存
function combine(a,b){
	return Buffer.concat([hexStrToBuf(a),hexStrToBuf(b)])
}

// 封装siphash函数，可输入数组或者字符串
function hash(){
	let param = Array.from(arguments)
	if(param.length == 1) return siphash.hash_hex(vector, param[0])
	let result = []
	for(let v of param){
		result.push(siphash.hash_hex(vector, v))
	}
	return result
}

